#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include "myinet.h"
#include <stdlib.h>
#include "tools.h"
#include "color.h"

int main(int argc, char *argv[])
{
    int sockfd, n;
    int portNumber;

    if (argc < 3){
        printf("Usage: %s <address> <port>\n", argv[0]);
        error_exit("please use the above format", NULL);
    }

    portNumber = atoi(argv[2]);

    char buffer[256];
    sockfd = getTcpClientSocket(argv[1], portNumber);
    info("connected to %s:%d", argv[1], portNumber);

    if (sockfd < 0)
        error_exit("failed to get socket", "");

    bzero(buffer, sizeof(buffer));

    for (;;) {
        printf(">");
        char* line = NULL;
        size_t n = 0;
        int size = getline(&line, &n, stdin);
        if (size <= 0)
            break;

        int sent = write(sockfd, line, size);
        if (sent < 0) {
            error_exit("write", 0);
        }

        int nbyte = read(sockfd, line, size);
        if (nbyte == 0)
        {
            printf("connection closed\n");
            exit(0);
        }
         
        if (nbyte < 0) {
            error_exit("read", 0);
        }
        line[size-1] = 0;

        printf("<get message: %s%s%s\n", FOREBLU, line, RESETTEXT);
    }

    printf("bye\n");

    close(sockfd);
    return 0;
}
